package com.uziot.bucket.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * import org.springframework.cloud.client.ServiceInstance;
 * import org.springframework.cloud.client.discovery.DiscoveryClient;
 * <p>
 * 获取每一个服务下面实例
 * 测试时，可以使用多个端口启动服务实例
 *
 * @author Lenovo
 */

@RestController
public class DiscoveryClientController {


    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/serviceurl")
    public Map<String, List<ServiceInstance>> serviceUrl() {
        Map<String, List<ServiceInstance>> msl = new HashMap<>(6);
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> sis = discoveryClient.getInstances(service);
            msl.put(service, sis);
        }
        return msl;
    }

    /**
     * 获取注册中心实例
     */
    @GetMapping("/getEurekaService")
    public List<Map<String, Object>> getEurekaService() {
        List<Application> sortedApplications = EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications();
        List<Map<String, Object>> list = new ArrayList<>();
        for (Application application : sortedApplications) {
            String name = application.getName();
            List<InstanceInfo> instances = application.getInstances();
            Map<String, Object> map = new HashMap<>();
            //服务名
            map.put("name", name);
            //服务状态
            map.put("instances", instances);
            list.add(map);
        }

        return list;
    }
}